package org.dreamwork.jasmine2.web.controls.chart.settings;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-5-12
 * Time: 10:22:49
 */
public class ChartSettingAttribute implements ISettingItem {
    private String name;
    private String value;
    private boolean xmlCddata;
    private Map<String, String> props = new HashMap<String, String> ();

    public ChartSettingAttribute () {
    }

    public ChartSettingAttribute (String name, String value) {
        this.name = name;
        this.value = value;
    }

    public ChartSettingAttribute (String name, String value, boolean xmlCddata) {
        this.name = name;
        this.value = value;
        this.xmlCddata = xmlCddata;
    }

    public void setProperty (String name, String value) {
        props.put (name, value);
    }

    @Override
    public String toString () {
        StringBuilder builder = new StringBuilder ();
        builder.append ('<').append (name);
        for (String key : props.keySet ())
            builder.append (' ').append (key).append ("=\"").append (props.get (key)).append ('"');
        builder.append ('>');
        if (xmlCddata) {
            builder.append ("<![CDATA[").append (value).append ("]]>");
        } else {
            builder.append (value);
        }
        builder.append ("</").append (name).append ('>');
        return builder.toString ();
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public String getValue () {
        return value;
    }

    public void setValue (String value) {
        this.value = value;
    }

    public boolean isXmlCddata () {
        return xmlCddata;
    }

    public void setXmlCddata (boolean xmlCddata) {
        this.xmlCddata = xmlCddata;
    }

    public static ChartSettingAttribute parse (Element element) {
        Node first = element.getFirstChild ();
        if (first != null) {
            if (first.getNodeType () == Node.TEXT_NODE)
                return new ChartSettingAttribute (element.getNodeName (), first.getNodeValue ());
            else if (first.getNodeType () == Node.CDATA_SECTION_NODE)
                return new ChartSettingAttribute (element.getNodeName (), first.getNodeValue (), true);
        }
        return null;
    }
}